package luj.tool.jnproxyan.proxy.network.socks.cmd.connect;

import luj.bean.api.BeanContext;
import luj.bean.api.bean.Bean;
import luj.cluster.api.actor.Tellable;
import luj.net.api.server.FrameDataReceiver;
import luj.tool.jnproxyan.framework.lujnet.ConnState;
import luj.tool.jnproxyan.proxy.network.socks.actor.root.message.request.connect.ReqConnectMsg;

public class CmdConnectHandler {

  public CmdConnectHandler(ConnState connState, BeanContext lujbean) {
    _connState = connState;
    _lujbean = lujbean;
  }

  /**
   * @see luj.tool.jnproxyan.proxy.network.socks.actor.root.message.request.connect.OnReqConnect#onHandle
   */
  public FrameDataReceiver handle() {
    Bean<ReqConnectMsg> msg = _lujbean.createBean(ReqConnectMsg.class);
    msg.setField(m -> m::version, _connState.getVer());
    msg.setField(m -> m::methods, _connState.getMethods());
    msg.setField(m -> m::cmd, _connState.getCmd());

    Long reqId = _connState.getReqId();
    msg.setField(m -> m::reqId, reqId);

    String targetHost = _connState.getDstAddr();
    msg.setField(m -> m::targetHost, targetHost);
    msg.setField(m -> m::targetPort, _connState.getDstPort());

    Tellable socksRef = _connState.getSocksRef();
    socksRef.tell(msg.getValueInstance());

    return new C2pReceiverV2(socksRef, reqId, _lujbean);
  }

//  private static final Logger LOG = LoggerFactory.getLogger(CmdConnectHandler.class);

  private final ConnState _connState;
  private final BeanContext _lujbean;
}
